package com.example.test622.ui.live

import android.util.Log
import androidx.lifecycle.viewModelScope
import com.example.common.mvi.BaseViewModel
import com.example.test622.ui.home.HomeIntent
import com.example.test622.ui.home.HomeState
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class LiveViewModel:BaseViewModel<LiveIntent,LiveState>() {
	init {
		viewModelScope.launch {
			intent.consumeAsFlow().collect{
				when(it){
					is LiveIntent.getRecommon->LoadCommon(it.page,it.size)
					else -> {
						// 处理未知的 intent 类型
						Log.e("UnknownIntent", "Received an unknown intent: $it")
						// 可以考虑发布一个状态表示处理失败或忽略此事件
					}
				}
			}
		}
	}
	
	private suspend fun LoadCommon(page: Int, size: Int) {
		val video = try {
			val res = service.getRecommendMutilVideo(page,size)
			if(res.code == 0){
				LiveState.RecommonSuccess(res)
			}else{
				LiveState.loadFail(res.msg)
			}
		}catch (e:Exception){
			Log.e("LoadCommon", e.message?:"Unexpected error occurred")
			LiveState.loadFail(e.message?:"")
		}
		state.postValue(video)
	}
}
